package org.example.ams.task.taskBean;

import lombok.Data;
import org.example.ams.entity.system.SysScheduled;
import org.example.ams.task.annotation.Task;
import org.example.ams.task.annotation.TaskGroup;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Data
public abstract class  AbstractTask {
    protected String taskGroupName = null;
    protected String beanId = null;
    protected List<SysScheduled> tasks = null;

    public AbstractTask() {
        Class<? extends AbstractTask> clazz = this.getClass();
        // 判断是否有@TaskGroup和@Component注解，有就封装上面的属性
        if (clazz.isAnnotationPresent(TaskGroup.class) && clazz.isAnnotationPresent(Component.class)) {
            TaskGroup taskGroup = clazz.getAnnotation(TaskGroup.class);
            Component component = clazz.getAnnotation(Component.class);
            this.taskGroupName = taskGroup.taskGroupName();
            String value = component.value();
            if (value == null || value.equals("")) {
                value = clazz.getSimpleName().substring(0,1).toLowerCase() + clazz.getSimpleName().substring(1);
            }
            this.beanId = value;
            Method[] methods = clazz.getDeclaredMethods();
            if (methods != null && methods.length > 0) {
                SysScheduled sysScheduled = null;
                tasks = new ArrayList();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(Task.class)) {
                        sysScheduled = new SysScheduled();
                        Task task = method.getAnnotation(Task.class);
                        sysScheduled.setScheduledName(task.taskName());
                        sysScheduled.setId(task.taskId());
                        sysScheduled.setMethodName(method.getName());
                        tasks.add(sysScheduled);
                    }
                }
            }
        }
    }
}
